<template>
  <div>
    <span>设为会员</span>
    <el-form
      :rules="formRules"
      ref="formRef"
      label-width="120px"
      :model="formData"
    >
      <div class="navLine">会员信息</div>
      <el-form-item label="微信头像">
        <img
          :src="avatarUrl"
          style="width: 40px; height: 40px; border-radius: 3px"
          alt
        />
      </el-form-item>
      <el-form-item label="微信昵称">{{ nikeName }}</el-form-item>
      <el-form-item prop="phone" label="手机号">
        <el-input style="width: 304px" v-model="formData.phone"></el-input>
      </el-form-item>
      <el-form-item prop="code" label="验证码">
        <el-input
          style="width: 200px; margin-right: 12px"
          v-model="formData.code"
        ></el-input>
        <el-button
          :disabled="formCode.isDisabled"
          @click="getVertifyCode('formData')"
          >{{ formCode.buttonName }}</el-button
        >
      </el-form-item>
      <div class="navLine">会员卡信息</div>
      <el-form-item label="选择会员等级" prop="rankCode">
        <el-select
          style="width: 304px"
          @change="memberChange"
          v-model="formData.rankCode"
        >
          <el-option
            v-for="item in rankOptions"
            :key="item.rankCode"
            :label="`${item.rankName}(LV${item.rankCode})`"
            :value="item.rankCode"
          ></el-option>
        </el-select>
        <br />
        <!-- <span style="color: #999">{{ privilegeInfo }}</span> -->
      </el-form-item>
    </el-form>
    <div class="pageButtom">
      <el-button @click="$router.push({ name: 'list' })">取消</el-button>
      <el-button type="primary" @click="onOk">确定</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Ref } from "vue-property-decorator";
import { getMemberCardRank, setMember, sendCode } from "@/api/customer/member";
import {phoneReg} from '@/libs/validate'

@Component
export default class Member extends Vue {
  @Ref()
  readonly formRef: HTMLFormElement;

  // 微信昵称
  nikeName = "";

  // 微信头像
  avatarUrl = "";

  // 验证码
  formCode: any = {
    buttonName: "获取验证码",
    isDisabled: false,
    time: 60,
  };

  // 手机号会员等级
  formData = {
    phone: null,
    code: "",
    rankCode: "",
  };

  // 会员下拉选项
  rankOptions: any[] = [];

  // 权益简介
  privilegeInfo = "";

  // 表单校验规则
  formRules = {
    phone: [{ required: true, validator: this.validPhone, trigger: "blur" }],
    code: [{ required: true, message: "输入验证码", trigger: "blur" }],
    rankCode: [
      { required: true, message: "请选择会员等级", trigger: "change" },
    ],
  };

  mounted() {
    this.nikeName = this.$route.params.nikeName;
    this.avatarUrl = this.$route.params.img;
    this.getRankList();
  }

  // 等级下拉列表数据请求
  getRankList() {
    getMemberCardRank(null).then((res) => {
      if (res.code === 200) {
        this.rankOptions = res.data || [];
      }
    });
  }

  memberChange(val) {
    const curMember = this.rankOptions.find((v) => v.rankCode == val) || {};
    const privilegList = (curMember.memberPrivilegeVos || []).filter(
      (v) => v.isSelected == 1,
    );
    this.privilegeInfo = `该等级会员卡享受${privilegList
      .map((v) => v.privilegeName)
      .join("、")}规则名称权益`;
  }

  // 获取验证码
  async getVertifyCode(formName) {
    try {
      let valid = '' as any
      this.formRef.validateField('phone',res => {
        valid = res
      });
      console.log(valid)
      if(valid) return;
      const res = await sendCode({
        phone: this[formName].phone,
      });
      if (res.code === 200) {
        this.formCode.isDisabled = false;
        this.$message.success("验证码发送成功！");
      } else {
        this.$message.warning("验证码发送失败！");
      }
      this.formCode.isDisabled = true;
      const interval = window.setInterval(() => {
        this.formCode.buttonName = `${this.formCode.time}秒后重新发送`;
        --this.formCode.time;
        if (this.formCode.time < 0) {
          this.formCode.buttonName = "重新发送";
          this.formCode.time = 60;
          this.formCode.isDisabled = false;
          window.clearInterval(interval);
        }
      }, 1000);
    } catch (e) {
      console.log(e);
      this.$message.warning(e);
    }
  }

  // 号码校验
  validPhone(rule, value, callback) {
    if (!value) {
      callback(new Error("请输入电话号码"));
    } else if (!this.isvalidPhone(value)) {
      callback(new Error("请输入正确的11位手机号码"));
    } else {
      callback();
    }
  }

  // 判断是否为有效手机号
  isvalidPhone(str) {
    return phoneReg.test(str);
  }

  // 确认提交
  onOk() {
    this.formRef.validate((valid) => {
      if (valid) {
        try {
          setMember({
            userId: this.$route.params.id,
            rankCode: this.formData.rankCode,
            phone: parseInt(this.formData.phone, 10),
            code: parseInt(this.formData.code, 10),
          })
            .then(() => {
              this.$message.success("会员设置成功");
              this.$router.push({
                name: "member",
              });
            })
            .catch((error) => {
              this.$message.error(error);
            });
        } catch (err) {
          console.log(err);
        }
      }
    });
  }
}
</script>

<style lang="scss" scoped>
@include b(navLine) {
  margin-top: 40px;
  margin-bottom: 40px;
  height: 40px;
  display: flex;
  -webkit-box-align: center;
  align-items: center;
  background-color: #f8f8f8;
  padding-left: 30px;
  font-weight: bold;
}

@include b(pageButtom) {
  margin-top: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
